package pe.com.rimac.portal.service.paperless.impl;

import java.rmi.RemoteException;

import pe.com.rimac.portal.common.config.ServiceConfig;
import pe.com.rimac.portal.common.exception.ServiceException;
import pe.com.rimac.portal.service.paperless.PaperlessService;
import pe.com.rimac.portal.service.paperless.model.PaperlessRequest;
import pe.com.rimac.portal.service.paperless.model.TipoRetorno;
import cl.paperless.core.asp.online.ws.proxy.OnlineProxy;

/**
 * @author Synopsis S.A
 *
 */
public class PaperlessServiceImpl implements PaperlessService
{
	private ServiceConfig serviceConfig;
	private OnlineProxy port;

	/**
	 * @param serviceConfig
	 */
	public PaperlessServiceImpl(ServiceConfig serviceConfig)
	{
		this.serviceConfig = serviceConfig;
		this.port = new OnlineProxy();
		this.port.setEndpoint(serviceConfig.getProperty("paperless.ws.url"));
	}

	/**
	 * @see pe.com.rimac.portal.service.paperless.PaperlessService#obtenerURLFactura(pe.com.rimac.portal.service.paperless.model.PaperlessRequest,
	 *      pe.com.rimac.portal.service.paperless.model.TipoRetorno, java.lang.String, java.lang.String)
	 */
	@Override
	public String obtenerURLFactura(PaperlessRequest request, TipoRetorno tipoRetorno, String username, String password)
			throws ServiceException
	{
		String response = invoke(serviceConfig.getProperty("ruc.rimac"), username, password, request.getTipoDocumento()
				.getIntValue(), request.getFolio(), tipoRetorno.getValue());
		return procesarResponse(response);
	}

	/**
	 * Realiza la invocaci&oacute;n al servicio paperless.
	 * 
	 * @param ruc
	 * @param login
	 * @param password
	 * @param tipoDocumento
	 * @param folio
	 * @param tipoRetorno
	 * @return
	 */
	private String invoke(String ruc, String login, String password, Integer tipoDocumento, String folio,
			Integer tipoRetorno)
	{
		try
		{
			return this.port.onlineRecovery(ruc, login, password, tipoDocumento, folio, tipoRetorno);
		}
		catch (RemoteException e)
		{
			throw new ServiceException("Ocurrio un error al consultar el servicio Paperless", e);
		}
	}

	/**
	 * Procesa la respuesta enviada por el servicio Paperless.
	 * 
	 * @param response
	 * @return
	 */
	private String procesarResponse(String response)
	{
		int start = response.indexOf("http");
		int end = response.indexOf("</Mensaje>");
		if (start != -1)
		{
			return response.substring(start, end);
		}
		throw new ServiceException("Ocurrio un error al obtener la factura electronica.");
	}
}